import React, {PropsWithChildren, useEffect, useState} from 'react'
import Taro, {useLoad} from "@tarojs/taro";
import {getMarketDetail, updateMarket} from "../apis/MarketsApi";
import MarketEditForm from "../components/MarketEditForm";
import marketPageStackStore from "../store/MarketPageStackStore";
import {observer} from "mobx-react";
import MyNavigationBar from "../components/MyNavigationBar";

export interface MarketEditProps extends PropsWithChildren {

}

const MarketEdit: React.FC<MarketEditProps> = ({}) => {
    const [id, setId] = useState<number>()
    useLoad((params) => {
        setId(Number(params.id))
    })
    let detail = marketPageStackStore.detail;
    useEffect(() => {
        if (id && !detail) {
            getMarketDetail(id).then(response => {
                marketPageStackStore.setDetail(response.data)
            })
        }
    }, [id,detail]);
    return <>
        <MyNavigationBar>编辑卖场</MyNavigationBar>
        {!!detail && <MarketEditForm initialValue={{
            name: detail.name,
            excludeBrandIds: detail.excludeBrands.map(it => it.id),
            saleManagerId: detail.saleManager?.id,
            shoppingGuideIds: detail.shoppingGuides.map(it => it.id)
        }} onConfirm={async (value,data) => {
            await updateMarket(id!!, value)
            marketPageStackStore.updateDetail({
                ...detail!,
                ...data,
            })
            Taro.navigateBack()
        }}/>}
    </>
}

export default observer(MarketEdit)


